<?php
namespace User\Controller;
use Think\Controller;
use Think\Crypt;
use Org\Net;
 /**
 *  前台分销模块
 */
class ShopController extends CkController {
    
    //分销产品
    public function index()
    {   
        $key=I('get.key');
        $M=M("shop_item");
        if($key){
            $where['title']=array('like', '%'.$key.'%');
            $M->where($where);
        }
        $data['uid']=session("user.id");
         $uid=de_crypt($data['uid']);
         if($uid){
            $data['user']=M('user')->where('id='.$uid)->find();
         }
        $data['shop_item']= $M->order('tj asc , id asc')->select();
        $data['title']="分销中心";
        $this->assign($data);
        $this->display();
    }
    

    //产品内容
    public function item()
    {   
        $id= (int)I('get.id');
        $data['item']= M('shop_item')->where(array('id'=>$id))->find();
        if(!$data['item']){ $this->error("商品不存在!");}
        $data['item']['suk']=json_decode($data['item']['suk'],true);
        $data['news']=D("NewsView")->where(array('News.item_id'=>$id))->select();
        $data['title']= $data['item']['title'];
        $this->assign($data);
        $this->display();
    }


    //订购页面
    public function buy()
    {   
        $item_id=(int)I('get.item_id');
        $news_id=(int)I('get.news_id');
        $data['uid']= I('get.uid');
        $data['item']= M('shop_item')->where(array('id'=>$item_id))->find();
        $data['title']= $data['item']['title'];
        if(!$data['item']){
            $this->error("商品不存在.");
        }
        if($news_id)
        {
          $data['news']=M('shop_news')->where(array('id'=>$news_id))->find();
          $data['title']= $data['news']['title'];
        }
        $this->assign($data);
        $this->display();
    }
    

    //订单处理页面
    
    public function buy_do()
    {
       if(!IS_POST) die('404');
       $order_num=cookie('order_num');
       if($order_num >=C("ORDER_NUM")){
          $this->error("Please don't repeat the order!");
       }
       $order['order']=$data=I('post.');
       $data['uid']= de_crypt($data['uid']);
       $data['item_id']= (int)$data['item_id'];
       if($data['item_id']){
           $item=M('shop_item')->field('suk')->where(array('id'=>$data['item_id']))->find();
           $suk= json_decode($item['suk'],true);
           $suk_key=$data['suk_key'];
           $suk= $suk[$suk_key];
           $data['suk_name']= $suk['name']; //重新获取一下SUK 防止前端修改
           $data['suk_price']= $suk['price'];
           $data['suk_ticheng']= $suk['ticheng'];
           $data['type']=1;
           $data['time'] = time();
           $order['order']['order_id']=$data['order_id'] = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
           $data['ip'] = get_ip();
           $data['ll_url']= $_SERVER['HTTP_REFERER'];
       }else{
           die("no item");
       }
       if(M('shop_order')->add($data)!==false){
          cookie('order_num',$order_num +1,3600); 
          $this->assign($order);
          $this->display();
          if(C('ORDER_SMS')){
          //短信通知
          $apikey = SMSAPIKEY;
          $smsqm= C('ORDER_SMSQM');
          $tpl_id = C("ORDER_SMS_ID");
          $tpl_value="#code#="."2222"."&#company#=".$smsqm;
          $sms=$this->tpl_send_sms($apikey,$tpl_id,$tpl_value,$order['order']['tel']);
          //die($sms);
          }
       }

    }
 
   
       /**
    * 模板接口发短信
    * apikey 为云片分配的apikey
    * tpl_id 为模板id
    * tpl_value 为模板值
    * mobile 为接受短信的手机号
    */
    private function tpl_send_sms($apikey, $tpl_id, $tpl_value, $mobile){
        $url="http://yunpian.com/v1/sms/tpl_send.json";
        $encoded_tpl_value = urlencode("$tpl_value");  //tpl_value需整体转义
        $mobile = urlencode("$mobile");
        $post_string="apikey=$apikey&tpl_id=$tpl_id&tpl_value=$encoded_tpl_value&mobile=$mobile";
        return $this->sock_post($url, $post_string);
    }



    private function send_sms($apikey, $text, $mobile){
        $url="http://yunpian.com/v1/sms/send.json";
        $encoded_text = urlencode("$text");
        $mobile = urlencode("$mobile");
        $post_string="apikey=$apikey&text=$encoded_text&mobile=$mobile";
        return $this->sock_post($url, $post_string);
    }



    /**
    * url 为服务的url地址
    * query 为请求串
    */
    private function sock_post($url,$query){
        $data = "";
        $info=parse_url($url);
        $fp=fsockopen($info["host"],80,$errno,$errstr,30);
        if(!$fp){
            return $data;
        }
        $head="POST ".$info['path']." HTTP/1.0\r\n";
        $head.="Host: ".$info['host']."\r\n";
        $head.="Referer: http://".$info['host'].$info['path']."\r\n";
        $head.="Content-type: application/x-www-form-urlencoded\r\n";
        $head.="Content-Length: ".strlen(trim($query))."\r\n";
        $head.="\r\n";
        $head.=trim($query);
        $write=fputs($fp,$head);
        $header = "";
        while ($str = trim(fgets($fp,4096))) {
            $header.=$str;
        }
        while (!feof($fp)) {
            $data .= fgets($fp,4096);
        }
        return $data;
    }

}
